<?php
/**
* @author moufer<moufer@163.com>
* @copyright (c)2001-2011 Moufersoft
* @website www.modoer.com
*/
_G('loader')->model('tool',FALSE);
class msm_tool_rebuildbranch extends msm_tool {

    protected $name = '重建所有分店统计数据';
    protected $descrption = '清空现有分店统计，重新对整站分店进行关联统计（只统计开启“添加分店”功能的主题分类）。';
    protected $acttype = 'rebuild';

    public function run() 
    {
        $step = _get('step', 1, MF_INT_KEY);
        if($step < 1 || $step > 2) {
            $this->message = '操作步骤不存在！';
            $this->completed = true;
        } else {
            $fun = 'step_'.$step;
            $this->$fun();
        }
    }

    protected function step_1()
    {
        _G('db')->from('dbpre_subject_branch')->clear_table();
        _G('db')->from('dbpre_subject_branch_index')->clear_table();
        $this->message = 'step 1:分店统计数据清空...';
        $this->params['step']   = 2;
    }

    protected function step_2()
    {
        $start = _get('start', 0, MF_INT_KEY);
        $offset = _get('offset', 300, MF_INT_KEY);
        $list = _G('db')->from('dbpre_subject')
            ->where_not_equal('subname', '')->order_by('sid')
            ->limit($start, $offset)->get();
        if(!$list) {
            $this->completed = true;
        } else {
            while ($val = $list->fetch_array()) {
                $this->build($val);
            }
            $list->free_result();
            $this->params['step']   = 2;
            $this->params['start']  = $start + $offset;
            $this->params['offset'] = $offset;
            $this->message = 'step 2:正在重建分站统计数据...'.($start).'-'.($this->params['start']);
        }
    }

    protected function build($shop)
    {
        static $configs = null;
        if(!$shop['subname']) return;
        if(is_null($configs[$shop['pid']])) {
            $configs[$shop['pid']] = $this->use_subbranch($shop['pid']);
        }
        if(!$configs[$shop['pid']]) return;
        $branch_mdl = _G('loader')->model('item:branch');
        $branch_mdl->add_branch($shop['sid'], $shop['name'], $shop['city_id']);
    }

    protected function use_subbranch($pid)
    {
        $category = $list = _G('db')->from('dbpre_category')->where('catid', $pid)->get_one();
        if(!$category) return false;
        if(!$category['config']) return false;
        $config = unserialize($category['config']);
        return (boolean)$config['use_subbranch'];
    }
}

/** end */